﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Collections;

namespace lib
{
    /// <summary>
    ///FileDownload 的摘要说明
    /// </summary>
    public class FileDownload
    {
        private string filepath = string.Empty;
        private FileStream fs = null;
        private HttpResponse response = null;
        private Hashtable errlist = new Hashtable();
        public FileDownload(HttpResponse res, string path)
        {
            this.response = res;
            this.filepath = path;
        }
        private bool checkFile(FileInfo file)
        {
            if (!file.Exists)
            {
                errlist.Add("文件检查", "需要下载的文件不存在");
                return false;
            }
            else
            { return true; }
        }
        /// <summary>
        /// 下载
        /// </summary>
        public void doDownload()
        {
            try
            {
                FileInfo fi = new FileInfo(filepath);
                if (!checkFile(fi))
                { return; }
                response.ContentType = "application/octet-stream";
                response.AddHeader("Content-Disposition", "attachment; filename=" + fi.Name);
                fs = File.OpenRead(filepath);
                byte[] b = new byte[1024 * 200];
                long downloadlenth = 0;
                long totallenth = fs.Length;
                int i = 0;
                while ((i = fs.Read(b, 0, b.Length)) > 0)
                {
                    response.OutputStream.Write(b, 0, b.Length);
                    response.Flush();
                    downloadlenth += i;
                }
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);
            }
            finally
            {
                if (fs != null)
                { fs.Dispose(); }
            }
        }
    }
}
